package com.hq.door.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hq.door.dao.IParentDao;
import com.hq.door.dao.TClassDAO;
import com.hq.door.dao.TOutRequestDAO;
import com.hq.door.dao.TRecordsDAO;
import com.hq.door.dao.TStudentDAO;
import com.hq.door.dto.Pagination;
import com.hq.door.dto.Parent;
import com.hq.door.dto.ParentApplyFront;
import com.hq.door.dto.ParentInfoBack;
import com.hq.door.dto.ParentParams;
import com.hq.door.dto.ParentRecordFront;
import com.hq.door.pojo.TClass;
import com.hq.door.pojo.TOutRequest;
import com.hq.door.pojo.TParent;
import com.hq.door.pojo.TRecords;
import com.hq.door.pojo.TStudent;
import com.hq.door.service.IParentService;

/**
 * 作者：袁健宝
 * 日期：2016年12月31日 上午4:40:36
 */
@Service("parentService")
public class ParentServiceImpl extends BaseServiceImpl<TParent> implements IParentService {

	@Autowired
	IParentDao parentDao;
	@Autowired
	TStudentDAO studentDao;
	@Autowired
	TOutRequestDAO outRequestDao;
	@Autowired
	TRecordsDAO recordDao;
	@Autowired
	TClassDAO classDao;


	@Override
	public List<TClass> queryClazzList(String grade) {
		List<TClass> clazzList = null;
		if(grade!=null&&!"".equals(grade)){
			String hql = "select t.id,t.name from TClass t where t.grade = ?";
			clazzList = classDao.queryList(hql, grade);
		}
		return clazzList;
	}


	@Override
	public List<TStudent> queryStudentList(String clazzName) {
		List<TStudent> studentList = null;
		if(clazzName!=null&&!"".equals(clazzName)){
			String hql = "select t.code,t.name from TStudent t inner join t.TClass c where c.name = ?";
			studentList = studentDao.queryList(hql, clazzName);
		}
		return studentList;
	}
	
	@Override
	public TParent wxBind(String parentName, 
			   String phoneNum,
			   String studentCode,
			   String clazz,
			   String reason){
		TParent parent = null;
		String hql = null;
		List<Object> conditions = new ArrayList<>();
		//根据学生姓名和班级 获取学生信息
		hql = "SELECT t from TStudent t where t.code = ?";
		conditions.add(studentCode);
		List<TStudent> studentList = studentDao.queryList(hql, conditions.toArray());
		if(studentList!=null&&studentList.size()>0){
			TStudent student = studentList.get(0);
			parent = new TParent();
			parent.setName(parentName);
			parent.setCode(phoneNum);
			parent.setTStudent(student);//关联学生信息
			parent.setReason(reason);	//设置申请绑定原因
			parent.setState("1");		//设置申请状态，1.申请中
			parent.setPassword("123456");//设置默认密码
			parent.setWeixinId("111111");//绑定微信ID（PC端测试，暂无微信ID）
			parent.setModifiedTime(new Timestamp(new Date().getTime()));//设置修改时间
			parentDao.save(parent);
		}
		return parent;
	}
	

	/**
	 * 查询家长信息总记录
	 * @return
	 */
	public Integer queryItemCount(String hql,Object ...params){
		Integer count = parentDao.getCount(hql,params);
		return count;
	}
	
	/**
	 * 根据家长查询 对应学生的刷卡记录
	 */
	public Pagination queryRecordsByParent(TParent tparent,ParentRecordFront prf){
		StringBuffer hql= null;
		StringBuffer hqlCount = null;
		StringBuffer hqlWhere = null;
		List<Object> conditions = null;
		String stuName = "";
		//2.使用学生的卡号（不是学号）
		hql = new StringBuffer("from TRecords as r");
		hqlCount = new StringBuffer("select count(r.id) from TRecords as r");
		hqlWhere = new StringBuffer(" where 1=1");
		conditions = new ArrayList<Object>();
		if(tparent!=null){
			String cardNo = tparent.getTStudent().getCordNo();
			stuName = tparent.getTStudent().getName();
			conditions.add(cardNo);
			for(Object obj : conditions){
				hqlWhere.append(" and r.cardNo=?");
			}
			if("1".equals(prf.getType())){//进校
				hqlWhere.append(" and r.inoutType=0 and r.isException=0");
			}
			if("2".equals(prf.getType())){//出校
				hqlWhere.append(" and r.inoutType=1 and r.isException=0");
			}
			if("3".equals(prf.getType())){//异常出入
				hqlWhere.append(" and r.isException=1");
			}
			conditions.add(prf.getStartDate());
			conditions.add(prf.getEndDate());
			hqlWhere.append(" and r.createTime>? and r.createTime<?");
		}else{
			hqlWhere.append(" and 1=0");
		}
		hqlWhere.append(" order by r.createTime desc");
		Integer pageStart = prf.getPageSize()*(prf.getPageNo()-1);
		hql.append(hqlWhere);
		hqlCount.append(hqlWhere);
		List<TRecords> tRecordList = outRequestDao.findPageObjects(hql.toString(), pageStart, prf.getPageSize(), conditions.toArray());
		Integer itemCount = outRequestDao.getCount(hqlCount.toString(), conditions.toArray());
		List<ParentRecordFront> prfList = ParentRecordFront.writeRecords(tRecordList,stuName);
		Pagination pagination = new Pagination(itemCount, "", prfList);
		return pagination;
	}

	/**
	 * 根据家长查询 对应学生的申请记录
	 */
	public Pagination queryApplysByParent(TParent tparent,ParentApplyFront paf){
		StringBuffer hql= null;
		StringBuffer hqlCount = null;
		StringBuffer hqlWhere = null;
		List<Object> conditions = null;
		//2.把学生id拼成参数，考虑多个学生id情况
		hqlWhere = new StringBuffer(" where 1=1");
		conditions = new ArrayList<Object>();
		if(tparent!=null){
			Integer stuId = tparent.getTStudent().getId();
			conditions.add(stuId);
			for(Object obj : conditions){
				hqlWhere.append(" and s.id=?");
			}
		}else{
			hqlWhere.append(" and 1=0");
		}
		hqlWhere.append(" order by o.startTime desc");
		//3.根据学生id查询外出申请记录
		hql = new StringBuffer("select o from TOutRequest o inner join fetch o.TStudent s")
							.append(" inner join fetch s.TClass c")
							.append(" inner join fetch c.TMajor m")
							.append(" inner join fetch m.TInstitute i");
		hqlCount = new StringBuffer("select count(o.id) from TOutRequest o inner join o.TStudent s");
		Integer pageStart = paf.getPageSize()*(paf.getPageNo()-1);
		hql.append(hqlWhere);
		hqlCount.append(hqlWhere);
		List<TOutRequest> toutRequestList = outRequestDao.findPageObjects(hql.toString(), pageStart, paf.getPageSize(), conditions.toArray());
		Integer itemCount = outRequestDao.getCount(hqlCount.toString(), conditions.toArray());
		List<ParentApplyFront> pafList = ParentApplyFront.writeApplies(toutRequestList);
		Pagination pagination = new Pagination(itemCount, "", pafList);
		return pagination;
	}
	
	/**
	 * 分页查询家长信息
	 * pageNo	第几页
	 * pageSize	每页多少条记录
	 * conditions	查询参数
	 */
	public Pagination queryParentListByPage(ParentParams pib){
		StringBuffer hql = new StringBuffer("select p from TParent p inner join fetch p.TStudent s")
							.append(" inner join fetch s.TClass c")
							.append(" inner join fetch c.TMajor m")
							.append(" inner join fetch m.TInstitute i");
		StringBuffer hqlCount = new StringBuffer("select count(p.id) from TParent p inner join p.TStudent s")
							.append(" inner join s.TClass c")
							.append(" inner join c.TMajor m")
							.append(" inner join m.TInstitute i");
		StringBuffer hqlWhere = new StringBuffer(" where 1=1");
		List<Object> conditions = new ArrayList<Object>();
		if(isString(pib.getInstituteName())&&!pib.getInstituteName().equals("")){
			hqlWhere.append(" and i.name=?");
			conditions.add(pib.getInstituteName());
		}
		if(isString(pib.getMajorName())&&!pib.getMajorName().equals("")){
			hqlWhere.append(" and m.name=?");
			conditions.add(pib.getMajorName());
		}
		if(isString(pib.getGradeName())||isString(pib.getClassName())){
			if(isString(pib.getGradeName())&&!pib.getGradeName().equals("")){
				hqlWhere.append(" and c.grade=?");
				conditions.add(pib.getGradeName());
			}
			if(isString(pib.getClassName())&&!pib.getClassName().equals("")){
				hqlWhere.append(" and c.name=?");
				conditions.add(pib.getClassName());
			}
		}
		if(isString(pib.getInfo())){
			hqlWhere.append(" and (p.name like ? or p.code like ? or s.name like ?)");
			conditions.add("%"+pib.getInfo()+"%");
			conditions.add("%"+pib.getInfo()+"%");
			conditions.add("%"+pib.getInfo()+"%");
		}
		hql.append(hqlWhere).append(" order by p.modifiedTime");
		hqlCount.append(hqlWhere).append(" order by p.modifiedTime");
		System.out.println(hql.toString());
		Integer pageStart = pib.getPageSize()*(pib.getPageNo()-1);
		List<TParent> tparentList = parentDao.findPageObjects(hql.toString(), pageStart, pib.getPageSize(), conditions.toArray());
		List<ParentInfoBack> pibs = ParentInfoBack.writeParent(tparentList);
		Integer itemCount = parentDao.getCount(hqlCount.toString(),conditions.toArray());
		Pagination pagination = new Pagination(itemCount, "", pibs);
		return pagination;
	}
	
	/**
	 * 查询所有家长信息
	 * @return
	 */
	public List<ParentInfoBack> queryParentList(){
		String hql = "select p from TParent p left join fetch p.TStudent";
		Object[] conditions = {};
		List<TParent> tparentList = parentDao.queryList(hql, conditions);
		List<ParentInfoBack> pibs = ParentInfoBack.writeParent(tparentList);
		return pibs;
	}
	
	/**
	 * 根据主键查询一条家长信息
	 * @param id
	 * @return
	 */
	public ParentInfoBack queryParent(Integer id){
		String hql = "select p from TParent p left join fetch p.TStudent where p.id=?";
		Object[] conditions = {
				id
		};
		TParent tparent = parentDao.queryOne(hql, conditions);
		ParentInfoBack pib = ParentInfoBack.writeParent(tparent);
		return pib;
	}

	/**
	 * 添加一条家长信息
	 */
	public String addParent(ParentInfoBack pib){
		TStudent student = getStudent(pib.getStuCode());
		TParent tparent = pib.readParent(pib);
		tparent.setTStudent(student);
		if(student==null){
			return "学号不存在";
		}
		parentDao.save(tparent);
		return "添加成功";
	}
	
	/**
	 * 修改一条家长信息
	 */
	public String modifyParent(ParentInfoBack pib){
		TStudent student = getStudent(pib.getStuCode());
		TParent tparent = pib.readParent(pib);
		tparent.setTStudent(student);
		if(student==null){
			return "学号不存在";
		}
		parentDao.update(tparent);
		return "修改成功";
	}
	
	/**
	 * 修改一条家长信息
	 * 添加微信id
	 */
	public TParent modifyParent(String mobile,String weixinId){
		TParent tparent = null;
		StringBuffer hql = new StringBuffer("from TParent tp inner join fetch tp.TStudent s inner join fetch s.TClass where tp.code = ?");
		tparent = parentDao.queryOne(hql.toString(), mobile);
		tparent.setWeixinId(weixinId);
		parentDao.update(tparent);
		return tparent;
	}
	
	/**
	 * 删除家长信息
	 */
	public Integer deleteParent(Integer ...pids){
		String result = "";
		int count = pids.length;
		if(pids!=null){
			for (int i = 0; i < pids.length; i++) {
				TParent tparent = parentDao.get(pids[i]);
				if(tparent!=null){
					count--;
					parentDao.delete(tparent);
				}
			}
		}
		return count;
	}
	
	/**
	 * 批量导入家长信息
	 */
	public String addParentList(List<Map<String,String>> list){
		List<ParentInfoBack> pibs = data2PIBS(list);
		Integer result = 0;
		ParentInfoBack pib=null;
		for(int index=0;pibs!=null&&index<pibs.size();index++){
			pib = pibs.get(index);
			TStudent student = getStudent(pib.getStuCode());
			TParent tparent = pib.readParent(pib);
			tparent.setTStudent(student);
			if(student==null){
				/*result =  "学号不存在";*/
			}else{
				parentDao.save(tparent);
				result++;
			}
		}
		return "成功导入数据"+result+"条！";
	}
	
	public static List<ParentInfoBack> data2PIBS(List<Map<String,String>> list){
		List<ParentInfoBack> pibs = new ArrayList<ParentInfoBack>();
		ParentInfoBack pib=null;
		for(int index=0;list!=null&&index<list.size();index++){
			Map<String,String> map = list.get(index);
			pib = new ParentInfoBack(
					map.get("家长姓名"),
					map.get("家长手机号"),
					map.get("家庭住址"),
					map.get("关系"),
					map.get("学号"),
					map.get("学生姓名"),
					map.get("家长密码"));
			pibs.add(pib);
		}
		return pibs;
	}
	
	/**
	 * 家长登录检查
	 */
	@Override
	public TParent check(Parent parent) {
		TParent tparent = null;
		StringBuffer hql = new StringBuffer("from TParent tp inner join fetch tp.TStudent s inner join fetch s.TClass where tp.code = ? and tp.password = ?");
		tparent = parentDao.queryOne(hql.toString(), parent.getUserName(),parent.getPassword()); 
		return tparent;	
	}

	/**
	 * 家长微信登录
	 * @param wexinId
	 * @return
	 */
	public TParent wxLogin(String weixinId) {
		String hql = "from TParent p inner join fetch p.TStudent s inner join fetch s.TClass where p.weixinId=?";
		TParent tparent = parentDao.queryOne(hql, weixinId);
		return tparent;
	}
	
	/**
	 * 判断一个对象是否是字符串，满足三个条件
	 * 		不为null
	 * 		类型为String
	 * 		不为""
	 * @param obj
	 * @return
	 */
	public boolean isString(Object obj){
		return obj==null||!(obj instanceof String)||"".equals(obj)?false:true;
	}
	
	/**
	 * 根据学号查询学生信息
	 * @param cardNo
	 * @return
	 */
	public TStudent getStudent(String code){
		String hql = "from TStudent stu where stu.code = ?";
		TStudent ts = studentDao.queryOne(hql, code);
		return ts;
	}

}
